from datetime import datetime
from typing import Optional
from uuid import uuid4

from beanie import Document
from pydantic import EmailStr, Field, BaseModel, field_serializer


class UserDocument(Document):
    user_id: str = Field(default_factory=lambda: str(uuid4()))
    username:str = Field()
    email: Optional[EmailStr] = None
    hashed_password: str
    is_active: bool = True
    is_superuser: bool = False
    is_verified: bool = False
    created_at: datetime = Field(default_factory=lambda: datetime.now())
    updated_at: datetime = Field(default_factory=lambda: datetime.now())

    class Settings:
        name = "users"
        validate_on_save = True

    class Config:
        arbitrary_types_allowed = True

class UserCreate(BaseModel):
    """用户创建模型"""
    username: str
    email: Optional[EmailStr] = None
    password: str
    phone: str
    phone_code: str

class UserResponse(BaseModel):
    """安全的用户响应模型，不包含敏感信息"""
    user_id: str
    username: str
    phone: Optional[str] = None
    email: Optional[EmailStr] = None
    is_active: bool
    is_superuser: bool
    is_verified: bool
    created_at: datetime
    role: Optional[str] = None

    @field_serializer('created_at')
    def serialize_created_at(self, dt: datetime) -> str | None:
        if dt:
            return dt.strftime("%Y-%m-%d %H:%M:%S")
        return None

    class Config:
        from_attributes = True



class UserLogin(BaseModel):
    """用户登录模型"""
    username: str
    password: str


class Token(BaseModel):
    """Token 响应模型"""
    access_token: str
    token_type: str

class TokenData(BaseModel):
    """Token 数据模型"""
    username: Optional[str] = None

